<template>
  <!-- 头部区域 -->
  <el-header class="header">
    <el-row :gutter="20">
      <!-- 左侧logo -->
      <el-col :span="21"><div class="grid-content bg-purple">
        <a href="#/">
          <i class="el-icon-eleme logo"></i>
          <span class="company">安踏后台管理系统</span>
        </a>
      </div></el-col>
      <!-- 右侧登出按钮、头像 -->
      <el-col :span="3"><div class="grid-content bg-purple">
        <el-dropdown trigger="hover" @command="handleCommand">
          <span class="el-dropdown-link">
            欢迎您，{{admin}}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item icon="el-icon-key" command='changePassword'>修改密码</el-dropdown-item>
            <el-dropdown-item icon="el-icon-warning-outline" command='quit'>退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div></el-col>
    </el-row>

    <!-- 修改密码框 -->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="500px">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        style="width: 400px;"
      >
        <el-form-item label="原密码" prop="oldPass">
          <el-input type="password" v-model="ruleForm.oldPass"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input type="password" v-model="ruleForm.newPass"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="changePassword('ruleForm')">提交</el-button>
          <el-button @click="$refs['ruleForm'].resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-header>
  
</template>

<script>
export default {
  data(){
    /* 旧密码 */
    const validateOldPass = async (rule, value, callback) => {
      /* 发送请求进行校验 */
      const {data} = await this.$request({
        url:`/user/pwd`,
        method:'post',
        data:{
          username:this.admin,
          password:value
        }
      })
      if (data.flag) {
        callback();
      } else {
        callback(new Error('密码不正确!'));
      }
    };
    /* 新密码 */
    const validateNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码!'));
      }else if(value == this.ruleForm.oldPass){
        callback(new Error('新旧密码不能保持一致!'));
      }
      else {
        callback();
      }
    };
    /* 确认密码 */
    var validateCheckPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码!'));
      } else if (value !== this.ruleForm.newPass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      /* localstorage数据 */
      admin:localStorage.getItem('admin'),
      token:localStorage.getItem('token'),
      /* 修改密码 */
      ruleForm:{
        oldPass:'',
        newPass:'',
        checkPass:''
      },
      dialogFormVisible:false,
      formLabelWidth:'100px',
      /* 正则 */
      rules: {
        //旧密码
        oldPass: [
          { required: true, message: "旧密码不能为空", trigger: "blur" },
          { validator: validateOldPass, trigger: "blur" }
        ],
        //新密码
        newPass: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { validator: validateNewPass, trigger: "blur" }  
        ], 
        //确认密码
        checkPass: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: validateCheckPass, trigger: "blur" }
        ]
      }
    }
  },
  methods: {
    /* 个人中心的修改密码、退出方法 */
    handleCommand(command) {
      /* 1. 退出：发送ajax请求，清空localStorage，返回登录页 */
      if(command=='quit'){
        this.logout({token:this.token})
      }
      /* 2. 修改密码前处理 */
      else if(command=='changePassword'){
        this.dialogFormVisible = true;
          this.$nextTick(() => {
          this.$refs["ruleForm"].resetFields();
        });
      }
    },
    /* 退出 */
    async logout(token){
      const {data} = await this.$request({
          url:'/user/logout',
          method:'post',
          data:{
            token
          }
      })
      /* flag为true时才允许退出，否则不允许(比如网络波动等情况) */
      if(data.flag){
        this.$notify({
            title: '成功',
            message: '退出成功！',
            type: 'success'
        });
        localStorage.removeItem('admin');
        localStorage.removeItem('token');
        this.$router.push('/login')
      }else{
        this.$notify({
            title: '失败',
            message: '退出失败！',
            type: 'error'
        });
      }
    },
    /* 修改密码 */
    changePassword(formName){
      this.$refs[formName].validate(async(valid) => {
        /* 校验通过，发送修改请求 */
        if(valid){
          const {data} = await this.$request({
            url:`/user/pwd`,
            method:'put',
            data:{
              username:this.admin,
              password:this.ruleForm.newPass
            }
          })
          /* 修改成功后，重新登录 */
          if(data.flag){
            this.$notify({
                title: '成功',
                message: '修改成功，请重新登录！',
                type: 'success'
            });
            this.logout({token:this.token})
          }else{
            this.$notify({
                title: '失败',
                message: '修改密码失败，请稍后重新修改！',
                type: 'error'
            });
            return
          }
        }else{
          this.$notify({
              title: '校验',
              message: '校验不通过！',
              type: 'error'
          });
          return
        }
        this.dialogFormVisible = false
      })
    }
  }

}
</script>

<style scoped>
.logo{
  font-size: 26px;
  color: #fc0;
  vertical-align: middle;
}
.company {
 position: absolute;
 color: white;
}
.el-dropdown-link{
  color: cornsilk;
}
</style>